package doughnut.xc.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Map;

public class ExcelExportEngine {

    public static XSSFWorkbook write2Excel(Object obj, XSSFWorkbook workbook) throws Exception {
        // 将需要导入的数据 转成map处理
        Map<String, Object> toMap = EntityUtils.entityToMap(obj);

        Sheet sheet = workbook.getSheetAt(0);
        Row row = null;
        Cell cell = null;
        for (int i = 0; i < 50; i++) {
            // 遍历指定行
            row = sheet.getRow(i);
            if (row != null) {
                // 指定列
                for (int j = 0; j < 50; j++) {
                    cell = row.getCell(j);
                    if (cell != null) {
                        fillData2Cell(cell, toMap);
                    }
                }
            } else {
                break;
            }
        }

        // 处理图片
        String photoPath = toMap.get("photo").toString();
        // 先创建一个字节输出流
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 读取图片
        File photoFile = ResourceUtils.getFile("classpath:" + photoPath);
        // BufferedImage是一个带缓冲区图像类,主要作用是将一幅图片加载到内存中
        BufferedImage bufferedImage = ImageIO.read(photoFile);
        // 把读取到图像放入到输出流中
        ImageIO.write(bufferedImage, "JPG", os); // ！！！"JPG"这个地方不能写死 可以优化！！！
        // 创建一个绘图控制类，负责画图
        Drawing patriarch = sheet.createDrawingPatriarch();
        // 获取图片位置
        XSSFSheet sheet1 = workbook.getSheetAt(1);
        int col1 = (int) sheet1.getRow(0).getCell(0).getNumericCellValue();
        int row1 = (int) sheet1.getRow(0).getCell(1).getNumericCellValue();
        int col2 = (int) sheet1.getRow(0).getCell(2).getNumericCellValue();
        int row2 = (int) sheet1.getRow(0).getCell(3).getNumericCellValue();
        ClientAnchor anchor = patriarch.createAnchor(0, 0, 0, 0, col1, row1, col2, row2);

        workbook.removeSheetAt(1);
        // 开始把图片写入到sheet指定的位置
        patriarch.createPicture(anchor,
                workbook.addPicture(os.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG)); // PICTURE_TYPE_JPEG写死了！！！
        return workbook;
    }

    // 单元格中数据是否和map的key一致，一致则填充数据
    private static void fillData2Cell(Cell cell, Map<String, Object> toMap) {
        CellType cellType = cell.getCellType();
        switch (cellType) {
            // 是函数类型
            case FORMULA:
                break;
            default:
                String cellVal = cell.getStringCellValue();
                Object o = toMap.get(cellVal);
                if (o != null) {
                    cell.setCellValue(o.toString());
                }
        }
    }

}
